<?php

namespace APPS\PAGES\CONTROLLERS\ADMIN;

use APPS\PAGES\MODELS\Page as PageModel;
use APPS\PAGES\MODELS\PagesTree;

class Index extends \T4\Controller {

	public function actionDefault() {

		$this->view->assign(
			'pages', PagesTree::getInstance()->getTree()
		);

		$newPage = new PageModel;
		$newPage->url->setExtra('append', '.html');
		$this->view->assign('page', $newPage);

		$result['content'] = $this->view->render('admin/index.html');

		return $result;
		
	}

	public function actionAdd() {

		$page = new PageModel();

		try {
			
			$page->fromArray($_POST);
			$page->save();
			$this->redirect('/admin/pages');
			
		} catch (Exception $e) {

			$result['errors'][] = $e->getMessage();
			
		}

		$this->view->assign('page', $page);
		$result['content'] = $this->view->render('admin/page.html');

		return $result;
		
	}

	public function actionEdit() {

		$page = PageModel::findByPK(intval($_REQUEST['id']));

		if ($_REQUEST['mode'] == 'edit') {

			try {

				$page->fromArray($_POST);
				$page->save();
				$this->redirect('/admin/pages');
				
			} catch (Exception $e) {

				$result['errors'][] = $e->getMessage();
				
			}
			
		}

		$page->url->setExtra('append', '.html');
		$this->view->assign('page', $page);

		$result['content'] = $this->view->render('admin/page.html');
		return $result;
		
	}

}